package com.future.WebSocket;

import com.future.allUtils.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * 握手拦截器
 */
@Component
@Slf4j
public class WebSocketAuthInterceptor implements HandshakeInterceptor {

    /**
     * 在握手请求前
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 1. 从请求头获取 Token
        String token = request.getHeaders().getFirst("Authorization");
        if (token == null) {
            return false; // 拒绝未携带 Token 的连接
        }
        // 3. 解析 JWT Token 获取用户 ID
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String id = claims.getSubject();
            if (id == null || id.isEmpty()) {
               log.error("WebSocket握手失败：Token 中未包含有效的用户ID");
                return false;
            }
            Long userId = Long.parseLong(id);
            if (userId == null || userId <= 0) {
                log.error("WebSocket握手失败：用户ID无效");
                return false;
            }

            // 4. 将用户ID存入 Session 属性，供后续使用
            attributes.put("userId", userId);
            log.info("WebSocket握手成功，用户ID: " + userId);
            return true; // 允许握手
        } catch (Exception e) {
            log.info("WebSocket握手失败：Token 解析错误 - " + e.getMessage());
            return false; // Token 解析失败，拒绝连接
        }
    }
    /**
     * 握手请求后
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
